package com.share.tool.generator.api_method;

import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.RootDoc;
import com.sun.tools.javadoc.Main;

import java.util.LinkedList;
import java.util.List;

public class DocUtil {
    /**
     * 会自动注入
     */
    private static RootDoc rootDoc;

    /**
     * 会自动调用这个方法
     *
     * @param root root
     * @return true
     */
    public static boolean start(RootDoc root) {
        rootDoc = root;
        return true;
    }

    /**
     * 生成文档
     *
     * @param javaFilePath 注意这里是.java文件绝对路径
     * @return 文档注释
     */
    public static List<String[]> execute(String javaFilePath) {
        List<String[]> list = new LinkedList<>();
        Main.execute(new String[]{"-doclet", DocUtil.class.getName(), "-docletpath",
                DocUtil.class.getResource("/").getPath(), "-encoding", "utf-8", javaFilePath});

        ClassDoc[] classes = rootDoc.classes();
        if (classes == null || classes.length == 0) {
            return list;
        }

        ClassDoc classDoc = classes[0];
        MethodDoc[] methods = classDoc.methods(false);
        for (MethodDoc method : methods) {
            boolean isPublic = method.isPublic();
            String returnType = method.returnType().typeName();
            if (!isPublic || "void".equals(returnType)) {
                continue;
            }

            String arr[] = new String[2];
            String classMethodName = method.toString();
            String rawCommentText = method.getRawCommentText();
//            String commentText = method.commentText();

            arr[0] = classMethodName;
            arr[1] = rawCommentText;
            list.add(arr);
        }
        return list;
    }
}
